/**
 * umi 运行时
 */
import React, { useState } from 'react';
import commonPkg from '@/utils/commonPkg';
import envData from '@/consts/environment';
import { getUrlParams } from '@/utils/urlUtil';

// 项目环境
var umiEnv = envData['umiEnv']

// 开发环境模拟 build环境 加载oss的代码资源
var ossPublicResource = envData['ossPublicResource'];

// oss 地址
var ossUrl = envData['ossUrl']

// 子服务配置
var appConfigData = [
  { name: 'user', port: '31780', projectName: 'web-microApp-module-user', env: umiEnv },
  { name: 'userConf',port: '31783',projectName: 'web-microApp-module-userConf', env: umiEnv },
  { name: 'vue2', port: '31785', projectName: 'web-microApp-module-vue2' , env: umiEnv},
  { name: 'vue3', port: '31786', projectName: 'web-microApp-module-vue3' , env: umiEnv},
  { name: 'purehtml',port: '31789', projectName: 'web-microApp-module-purehtml', env: umiEnv},
  { name: 'components',port: '31790', projectName: 'web-microApp-module-components', env: umiEnv},
];

// 获取服务配置
async function getApps() {
  // url参数
  var params = getUrlParams()

  var apps = appConfigData.map(item => {
    // oss地址
    var ossEntry = `${ossUrl}/${item.projectName}/dist/index.html`

    // 本地调试地址
    var entry = `//${envData['webUrl']}:${item.port}`

    var appItem = { name : item.name, entry:'' }

    // 远端oss资源地址
    if (item.env == 'production'|| ossPublicResource){
      appItem.entry = ossEntry
    }else{
      // 本地资源地址
      appItem.entry = entry
    }
    
    // url参数 debug模式
    var debug = params['debug']
    var fn = ()=>{  appItem.entry = `//${'localhost'}:${item.port}` }
    // 单个
    if(debug == item.name) fn()
    // 多个项目调试
    if(debug instanceof Array){
      debug.forEach((name)=>{
        if(name == item.name) fn()
      })
    }
    console.log()
    return appItem
  });
  return apps;
}


export const qiankun = async function () {
  var apps = await getApps()
  return {
    apps:apps,
    lifeCycles: {
      beforeLoad: props => { },
      beforeMount: props => { },
      afterMount: props => { },
      beforeUnmount: props => { },
      afterUnmount: props => { },
    },
  };
};


// 父应用传给子应用参数
export function useQiankunStateForSlave() {
  const [masterState, setMasterState] = useState({});

  return {
    masterState,
    setMasterState,
  };
}

export async function getInitialState() {
  return commonPkg;
}
